package com.gd.iot.energy.util;

import cn.hutool.core.util.StrUtil;
import com.gd.iot.energy.consts.SystemConsts;
import com.gd.iot.energy.pojo.superadmin.dto.AdminDTO;
import com.gd.iot.energy.pojo.superadmin.dto.RoleDTO;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 当前用户的信息
 *
 * @author kris
 * @date Created at 2020/8/3 16:53
 */
public class CurrentUserUtil {

    /**
     * 获取登录用户的信息
     * @return
     */
    public static AdminDTO getUserInfo(){
        return (AdminDTO) SecurityUtils.getSubject().getPrincipal();
    }

    /**
     * 获取登录用户的token
     * @return
     */
    public static String getUserToken(){
        final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader(SystemConsts.TOKEN_KEY);
        if(StrUtil.isBlank(token)){
            token = request.getHeader(SystemConsts.TOKEN_KEY.toLowerCase());
        }
        return token;
    }

    /**
     * 获取当前用户设备
     * @return
     */
    public static List<Integer> getCurrentUserEquipments(){

        AdminDTO userInfo = CurrentUserUtil.getUserInfo();
        List<RoleDTO> roles = userInfo.getRoles();

        if(roles==null || roles.isEmpty()){
            return new ArrayList<>();
        }
        List<String> equipments = new ArrayList<>();
        for (RoleDTO role : roles) {
            if(StrUtil.isNotBlank(role.getEquipmentIds())) {
                equipments.addAll(Arrays.asList(role.getEquipmentIds().split(",")));
            }
        }

        return CustomCollUtil.strListToIntegerList(equipments);
    }

    /**
     * 获取当前用户设备
     * @return
     */
    public static List<Integer> getCurrentUserAreaIds(){

        AdminDTO userInfo = CurrentUserUtil.getUserInfo();
        List<RoleDTO> roles = userInfo.getRoles();

        if(roles==null || roles.isEmpty()){
            return new ArrayList<>();
        }
        List<String> areaIds = new ArrayList<>();
        for (RoleDTO role : roles) {
            if(StrUtil.isNotBlank(role.getAreaIds())) {
                areaIds.addAll(Arrays.asList(role.getAreaIds().split(",")));
            }
        }

        return CustomCollUtil.strListToIntegerList(areaIds);
    }

    /**
     * 是否是超级管理员
     * @return
     */
    public static boolean isSuperAdmin(){
        AdminDTO userInfo = CurrentUserUtil.getUserInfo();
        for (RoleDTO role : userInfo.getRoles()) {
            if(SystemConsts.SUPER_ADMIN_NAME.equals(role.getName())){
                return true;
            }
        }
        return false;
    }
}
